package com.yycx.dbr.boot.task;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yycx.common.base.entity.EntityMap;
import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.module.bus.client.entity.hy.BusErpOrder;
import com.yycx.module.bus.client.entity.hy.BusErpOrderDetails;
import com.yycx.module.bus.client.enums.VoucherTypeEnum;
import com.yycx.module.bus.provider.service.BusCustomService;
import com.yycx.module.bus.provider.service.hy.BusErpOrderDetailsService;
import com.yycx.module.bus.provider.service.hy.BusErpOrderService;
import com.yycx.module.bus.provider.service.hy.HyOrderService;
import com.yycx.module.bus.provider.service.hy.HyRemoteOrderService;
import com.yycx.module.system.client.entity.SysCompany;
import com.yycx.module.system.client.entity.SysConfig;
import com.yycx.module.system.provider.service.BaseConfigService;
import com.yycx.module.system.provider.service.SysCompanyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;


@Component
@EnableScheduling
@Slf4j
public class HyOrderScheduledTask {


    @Autowired
    private HyRemoteOrderService hyRemoteOrderService;

    @Autowired
    private BusErpOrderDetailsService busErpOrderDetailsService;

    @Autowired
    private BusErpOrderService busErpOrderService;

    @Autowired
    private SysCompanyService sysCompanyService;

    @Autowired
    private BaseConfigService configService;

    @Autowired
    private HyOrderService orderService;
    @Autowired
    private BusCustomService customService;

    // 查询销售订单
    //@Scheduled(cron = "0 0 10-19 ? * MON-FRI")
    public void saleOrderTasks() {

        // 1 查询当天ERP销售订单
        // 2 订单详情记录到本地
        // 3 根据订单信息找到单位 、商品信息
        // 4 查询单位对应的凭证编号
        // 5 生成凭证
        String currentDay = getCurrentDay();
        List<SysCompany> cwErpList = getSysCompanies();
        Map<String, Long> erpMap = cwErpList.stream().collect(Collectors.toMap(c -> c.getCompanyErpInstance(), c -> c.getCompanyId()));
        for (SysCompany busCwErp : cwErpList) {
            //long saleOrderCount = hyRemoteOrderService.saleOrderCount(busCwErp.getCompanyErpInstance(), currentDay);
            //long count = busErpOrderDetailsService.count(new QueryWrapper<BusErpOrderDetails>().eq("date_format(createTime,'%Y-%m-%d')", currentDay).lambda().eq(BusErpOrderDetails::getHyDwCode, busCwErp.getCompanyCode()).eq(BusErpOrderDetails::getOrderType, VoucherTypeEnum.Xs.getCode()));
            //海鹰有新订单继续
            //if (saleOrderCount > count) {
            if (true) {
                //List<BusErpOrder> currentErpOrderList = busErpOrderService.list(new QueryWrapper<BusErpOrder>().eq("date_format(createTime,'%Y-%m-%d')", currentDay).lambda().eq(BusErpOrder::getHyDwCode, busCwErp.getCompanyCode()).eq(BusErpOrder::getOrderType, VoucherTypeEnum.Xs.getCode()));
                //List<String> orderNos = currentErpOrderList.stream().map(BusErpOrder::getOrderNo).collect(Collectors.toList());
                List<String> orderNos = new ArrayList<>();
                List<EntityMap> list = hyRemoteOrderService.saleOrderList(busCwErp.getCompanyErpInstance(), currentDay, CollUtil.isEmpty(orderNos) ? null : orderNos);
                if (CollUtil.isNotEmpty(list)) {
                    List<BusErpOrder> busErpOrderList = new ArrayList<>();
                    list.forEach(item -> {
                        BusErpOrder busErpOrder = BeanUtil.fillBeanWithMap(item, new BusErpOrder(), false);
                        BusErpOrder check = busErpOrderService.findByOrderNoAndType(busErpOrder.getOrderNo(), VoucherTypeEnum.Xs.getCode());
                        if (FlymeUtils.isNotEmpty(check)) {
                            busErpOrder.setOrderId(check.getOrderId());
                        }
                        busErpOrder.setOrderType(VoucherTypeEnum.Xs.getCode());
                        busErpOrder.setErpDbName(busCwErp.getCompanyErpInstance());
                        busErpOrder.setHyDwCode(busCwErp.getCompanyCode());
                        busErpOrder.setCompanyId(erpMap.get(busCwErp.getCompanyErpInstance()));
                        busErpOrderList.add(busErpOrder);
                    });
                    busErpOrderService.saveOrUpdateBatch(busErpOrderList);
                    busErpOrderDetailsService.remove(new QueryWrapper<BusErpOrderDetails>().lambda().eq(BusErpOrderDetails::getHyDwCode, busCwErp.getCompanyCode()).eq(BusErpOrderDetails::getOrderDate, currentDay).eq(BusErpOrderDetails::getOrderType, VoucherTypeEnum.Xs.getCode()));
                    List<EntityMap> orderDetailList = hyRemoteOrderService.saleOrderDetailList(busCwErp.getCompanyErpInstance(), currentDay, busErpOrderList.stream().map(BusErpOrder::getOrderNo).collect(Collectors.toList()));
                    List<BusErpOrderDetails> busErpOrderDetailsList = new ArrayList<>();
                    orderDetailList.forEach(item -> {
                        BusErpOrderDetails busErpOrderDetails = BeanUtil.fillBeanWithMap(item, new BusErpOrderDetails(), false);
                        busErpOrderDetails.setOrderType(VoucherTypeEnum.Xs.getCode());
                        busErpOrderDetails.setErpDbName(busCwErp.getCompanyErpInstance());
                        busErpOrderDetails.setHyDwCode(busCwErp.getCompanyCode());
                        busErpOrderDetailsList.add(busErpOrderDetails);
                    });
                    busErpOrderDetailsService.saveOrUpdateBatch(busErpOrderDetailsList);
                }
            }
        }
    }

    private String getCurrentDay() {
        SysConfig config = configService.getById(15);
        return (ObjectUtil.isNotNull(config) && StrUtil.isNotEmpty(config.getConfigVal())) ? config.getConfigVal() : DatePattern.NORM_DATE_FORMAT.format(DateUtil.date());
    }

    private List<SysCompany> getSysCompanies() {
        return sysCompanyService.list(new QueryWrapper<SysCompany>().lambda().eq(SysCompany::getCompanyErpState, 1));
    }


    // 查询采购订单
    // @Scheduled(cron = "0 */1 * * * ?")
    //@Scheduled(cron = "0 0 10-19 ? * MON-FRI")
    public void buyOrderTasks() {

        String currentDay = getCurrentDay();
        List<SysCompany> cwErpList = getSysCompanies();
        Map<String, Long> erpMap = cwErpList.stream().collect(Collectors.toMap(c -> c.getCompanyErpInstance(), c -> c.getCompanyId()));

        for (SysCompany busCwErp : cwErpList) {
            //long buyOrderCount = hyRemoteOrderService.buyOrderCount(busCwErp.getCompanyErpInstance(), currentDay);
            //long count = busErpOrderDetailsService.count(new QueryWrapper<BusErpOrderDetails>().eq("date_format(createTime,'%Y-%m-%d')", currentDay).lambda().eq(BusErpOrderDetails::getHyDwCode, busCwErp.getCompanyCode()).eq(BusErpOrderDetails::getOrderType, VoucherTypeEnum.Cg.getCode()));
            //海鹰有新订单继续
            //if (buyOrderCount > count) {
            if (true) {
                //List<BusErpOrder> currentErpOrderList = busErpOrderService.list(new QueryWrapper<BusErpOrder>().eq("date_format(createTime,'%Y-%m-%d')", currentDay).lambda().eq(BusErpOrder::getHyDwCode, busCwErp.getCompanyCode()).eq(BusErpOrder::getOrderType, VoucherTypeEnum.Cg.getCode()));
                //List<String> orderNos = currentErpOrderList.stream().map(BusErpOrder::getOrderNo).collect(Collectors.toList());
                List<String> orderNos = new ArrayList<>();

                List<EntityMap> list = hyRemoteOrderService.buyOrderList(busCwErp.getCompanyErpInstance(), currentDay, CollUtil.isEmpty(orderNos) ? null : orderNos);
                if (CollUtil.isNotEmpty(list)) {

                    List<BusErpOrder> busErpOrderList = new ArrayList<>();
                    list.forEach(item -> {
                        BusErpOrder busErpOrder = BeanUtil.fillBeanWithMap(item, new BusErpOrder(), false);
                        BusErpOrder check = busErpOrderService.findByOrderNoAndType(busErpOrder.getOrderNo(), VoucherTypeEnum.Cg.getCode());
                        if (FlymeUtils.isNotEmpty(check)) {
                            busErpOrder.setOrderId(check.getOrderId());
                        }
                        busErpOrder.setOrderType(VoucherTypeEnum.Cg.getCode());
                        busErpOrder.setErpDbName(busCwErp.getCompanyErpInstance());
                        busErpOrder.setHyDwCode(busCwErp.getCompanyCode());
                        busErpOrder.setCompanyId(erpMap.get(busCwErp.getCompanyErpInstance()));
                        busErpOrderList.add(busErpOrder);
                    });
                    busErpOrderService.saveOrUpdateBatch(busErpOrderList);
                    busErpOrderDetailsService.remove(new QueryWrapper<BusErpOrderDetails>().lambda().eq(BusErpOrderDetails::getHyDwCode, busCwErp.getCompanyCode()).eq(BusErpOrderDetails::getOrderDate, currentDay).eq(BusErpOrderDetails::getOrderType, VoucherTypeEnum.Cg.getCode()));

                    List<EntityMap> orderDetailList = hyRemoteOrderService.buyOrderDetailList(busCwErp.getCompanyErpInstance(), currentDay, busErpOrderList.stream().map(BusErpOrder::getOrderNo).collect(Collectors.toList()));
                    List<BusErpOrderDetails> busErpOrderDetailsList = new ArrayList<>();
                    orderDetailList.forEach(item -> {
                        BusErpOrderDetails busErpOrderDetails = BeanUtil.fillBeanWithMap(item, new BusErpOrderDetails(), false);
                        busErpOrderDetails.setOrderType(VoucherTypeEnum.Cg.getCode());
                        busErpOrderDetails.setErpDbName(busCwErp.getCompanyErpInstance());
                        busErpOrderDetails.setHyDwCode(busCwErp.getCompanyCode());
                        busErpOrderDetailsList.add(busErpOrderDetails);
                    });

                    busErpOrderDetailsService.saveOrUpdateBatch(busErpOrderDetailsList);
                }
            }
        }
    }


    // 查询销售订单计算 成本凭证
    // @Scheduled(cron = "0 */2 * * * ?")
    //@Scheduled(cron = "0 0 10-19 ? * MON-FRI")
    public void costOrderTasks() {

        // 1 查询当天ERP销售订单
        // 2 订单详情记录到本地
        // 3 根据订单信息找到单位 、商品信息
        // 4 查询单位对应的凭证编号
        // 5 生成凭证

        String currentDay = getCurrentDay();
        List<SysCompany> cwErpList = getSysCompanies();
        Map<String, Long> erpMap = cwErpList.stream().collect(Collectors.toMap(c -> c.getCompanyErpInstance(), c -> c.getCompanyId()));

        for (SysCompany busCwErp : cwErpList) {
            //long saleOrderCount = hyRemoteOrderService.saleCostCount(busCwErp.getCompanyErpInstance(), currentDay);
            //long count = busErpOrderDetailsService.count(new QueryWrapper<BusErpOrderDetails>().eq("date_format(createTime,'%Y-%m-%d')", currentDay).lambda().eq(BusErpOrderDetails::getHyDwCode, busCwErp.getCompanyCode()).eq(BusErpOrderDetails::getOrderType, VoucherTypeEnum.Cb.getCode()));
            //海鹰有新订单继续
            //if (saleOrderCount > count) {
            if (true) {
                //List<BusErpOrder> currentErpOrderList = busErpOrderService.list(new QueryWrapper<BusErpOrder>().eq("date_format(createTime,'%Y-%m-%d')", currentDay).lambda().eq(BusErpOrder::getHyDwCode, busCwErp.getCompanyCode()).eq(BusErpOrder::getOrderType, VoucherTypeEnum.Cb.getCode()));
                // List<String> orderNos = currentErpOrderList.stream().map(BusErpOrder::getOrderNo).collect(Collectors.toList());
                List<String> orderNos = new ArrayList<>();
                List<EntityMap> list = hyRemoteOrderService.saleCostList(busCwErp.getCompanyErpInstance(), currentDay, CollUtil.isEmpty(orderNos) ? null : orderNos);
                if (CollUtil.isNotEmpty(list)) {

                    List<BusErpOrder> busErpOrderList = new ArrayList<>();
                    list.forEach(item -> {
                        BusErpOrder busErpOrder = BeanUtil.fillBeanWithMap(item, new BusErpOrder(), false);
                        BusErpOrder check = busErpOrderService.findByOrderNoAndType(busErpOrder.getOrderNo(), VoucherTypeEnum.Cb.getCode());
                        if (FlymeUtils.isNotEmpty(check)) {
                            busErpOrder.setOrderId(check.getOrderId());
                        }
                        busErpOrder.setOrderType(VoucherTypeEnum.Cb.getCode());
                        busErpOrder.setErpDbName(busCwErp.getCompanyErpInstance());
                        busErpOrder.setHyDwCode(busCwErp.getCompanyCode());
                        busErpOrder.setCompanyId(erpMap.get(busCwErp.getCompanyErpInstance()));
                        busErpOrderList.add(busErpOrder);
                    });
                    busErpOrderService.saveOrUpdateBatch(busErpOrderList);
                    busErpOrderDetailsService.remove(new QueryWrapper<BusErpOrderDetails>().lambda().eq(BusErpOrderDetails::getHyDwCode, busCwErp.getCompanyCode()).eq(BusErpOrderDetails::getOrderDate, currentDay).eq(BusErpOrderDetails::getOrderType, VoucherTypeEnum.Cb.getCode()));

                    List<EntityMap> orderDetailList = hyRemoteOrderService.saleCostDetailList(busCwErp.getCompanyErpInstance(), currentDay, busErpOrderList.stream().map(BusErpOrder::getOrderNo).collect(Collectors.toList()));
                    List<BusErpOrderDetails> busErpOrderDetailsList = new ArrayList<>();
                    orderDetailList.forEach(item -> {
                        BusErpOrderDetails busErpOrderDetails = BeanUtil.fillBeanWithMap(item, new BusErpOrderDetails(), false);
                        busErpOrderDetails.setOrderType(VoucherTypeEnum.Cb.getCode());
                        busErpOrderDetails.setErpDbName(busCwErp.getCompanyErpInstance());
                        busErpOrderDetails.setHyDwCode(busCwErp.getCompanyCode());
                        busErpOrderDetailsList.add(busErpOrderDetails);
                    });

                    busErpOrderDetailsService.saveOrUpdateBatch(busErpOrderDetailsList);
                }

            }
        }
    }


    // 付款凭证 查询入库订单
    @Scheduled(cron = "0 0/2 9-19 * * ?")
    public void paymentOrderTasks() {
        // 1 查询当天ERP销售订单
        // 2 订单详情记录到本地
        // 3 根据订单信息找到单位 、商品信息
        // 4 查询单位对应的凭证编号
        // 5 生成凭证
        String currentDay = getCurrentDay();
        List<SysCompany> cwErpList = getSysCompanies();
        Map<String, Long> erpMap = cwErpList.stream().collect(Collectors.toMap(c -> c.getCompanyErpInstance(), c -> c.getCompanyId()));

        for (SysCompany busCwErp : cwErpList) {
            QueryWrapper<BusErpOrder> cq = new QueryWrapper<>();
            cq.eq("date_format(createTime,'%Y-%m-%d')", DatePattern.NORM_DATE_FORMAT.format(DateUtil.date()));
            cq.lambda().eq(BusErpOrder::getHyDwCode, busCwErp.getCompanyCode())
                .eq(BusErpOrder::getOrderType, VoucherTypeEnum.Fk.getCode());
            List<BusErpOrder> currentErpOrderList = busErpOrderService.list(cq);
            List<String> orderNos = currentErpOrderList.stream().map(BusErpOrder::getOrderNo).collect(Collectors.toList());
            //查询收付主付款记录
            List<EntityMap> entityMaps = hyRemoteOrderService.receiptPaymentOrderList("-1", busCwErp.getCompanyErpInstance(), currentDay, CollUtil.isEmpty(orderNos) ? null : orderNos);

            Map<String, String> mxCollect = entityMaps.stream().filter(b -> ObjectUtil.isNotNull(b.get("mxNo"))).collect(Collectors.toMap(b -> b.get("orderNo").toString(), b -> b.get("mxNo").toString(), (v1, v2) -> v1));

            if (CollUtil.isNotEmpty(entityMaps)) {
                orderNos = entityMaps.stream().map(e -> e.get("orderNo").toString()).distinct().collect(Collectors.toList());
                if (CollUtil.isEmpty(orderNos)) {
                    return;
                }
                Iterator<String> iterator = orderNos.stream().iterator();
                //按单据勾对
                List<String> orderNos1 = entityMaps.stream().filter(b -> ObjectUtil.isNull(b.get("mxNo"))).map(b -> b.get("orderNo").toString()).collect(Collectors.toList());
                //明细勾对
                List<String> orderNos2 = entityMaps.stream().filter(b -> ObjectUtil.isNotNull(b.get("mxNo"))).map(b -> b.get("orderNo").toString()).collect(Collectors.toList());
                //while (iterator.hasNext()) {
                for (int w = 0; w < orderNos.size(); w++) {
                    String orderNo11 = orderNos.get(w);
                    //String orderNo = iterator.next();
                    //查询入库单主
                    List<EntityMap> list = hyRemoteOrderService.purchasePaymentOrderList(busCwErp.getCompanyErpInstance(), currentDay, Arrays.asList(orderNo11));
                    if (CollUtil.isEmpty(list)) {
                        return;
                    }
                    List<BusErpOrder> busErpOrderList = new ArrayList<>();
                    list.forEach(item -> {
                        BusErpOrder busErpOrder = BeanUtil.fillBeanWithMap(item, new BusErpOrder(), false);
                        BusErpOrder check = busErpOrderService.findByOrderNoAndType(busErpOrder.getOrderNo(), VoucherTypeEnum.Fk.getCode());
                        if (FlymeUtils.isNotEmpty(check)) {
                            busErpOrder.setOrderId(check.getOrderId());
                        }
                        busErpOrder.setOrderType(VoucherTypeEnum.Fk.getCode());
                        busErpOrder.setErpDbName(busCwErp.getCompanyErpInstance());
                        busErpOrder.setHyDwCode(busCwErp.getCompanyCode());
                        busErpOrder.setCreateTime(DateUtil.date());
                        busErpOrder.setCompanyId(erpMap.get(busCwErp.getCompanyErpInstance()));
                        busErpOrderList.add(busErpOrder);
                    });
                    busErpOrderService.saveOrUpdateBatch(busErpOrderList);
                    List<BusErpOrderDetails> busErpOrderDetailsList = new ArrayList<>();

                    if (orderNos1.contains(orderNo11)) {

                        // t2.清单编码 orderNo,
                        List<EntityMap> orderDetailList = hyRemoteOrderService.purchasePaymentOrderDetailList(busCwErp.getCompanyErpInstance(), currentDay, Arrays.asList(orderNo11));

                        Map<String, List<EntityMap>> detailList = entityMaps.stream().filter(b -> ObjectUtil.isNull(b.get("mxNo"))).collect(Collectors.groupingBy(b -> b.get("orderNo").toString()));

                        orderDetailList.forEach(item -> {

                            BusErpOrderDetails busErpOrderDetails = BeanUtil.fillBeanWithMap(item, new BusErpOrderDetails(), false);
                            if (CollUtil.isNotEmpty(detailList)) {
                                for (String s : detailList.keySet()) {
                                    List<EntityMap> entityMaps1 = detailList.get(s);
                                    for (EntityMap entityMap : entityMaps1) {
                                        if (busErpOrderDetails.getOrderNo().equals(entityMap.get("orderNo"))) {
                                            busErpOrderDetails.setUpdateTime(entityMap.get("receiptDate"));
                                            break;
                                        }
                                    }
                                }
                            }
                            busErpOrderDetails.setOrderType(VoucherTypeEnum.Fk.getCode());
                            busErpOrderDetails.setErpDbName(busCwErp.getCompanyErpInstance());
                            busErpOrderDetails.setHyDwCode(busCwErp.getCompanyCode());
                            busErpOrderDetails.setCreateTime(DateUtil.date());

                            busErpOrderDetailsList.add(busErpOrderDetails);
                        });
                    }
                    if (orderNos2.contains(orderNo11)) {
                        String mxNo = mxCollect.get(orderNo11);
                        //按明细勾对
                        Map<String, String> proCollect = entityMaps.stream().filter(b -> ObjectUtil.isNotNull(b.get("mxNo"))).collect(Collectors.toMap(b -> b.get("productCode").toString() + "#" + b.get("productBatch").toString(), b -> b.get("productBatch").toString(), (v1, v2) -> v1));
                        List<EntityMap> orderDetailList3 = hyRemoteOrderService.purchasePaymentOrderDetailList(busCwErp.getCompanyErpInstance(), currentDay, Arrays.asList(orderNo11));
                        orderDetailList3.forEach(item -> {


                            BusErpOrderDetails busErpOrderDetails = BeanUtil.fillBeanWithMap(item, new BusErpOrderDetails(), false);
                            String o = proCollect.get(busErpOrderDetails.getProductCode() + "#" + busErpOrderDetails.getProductBatch());
                            if (StrUtil.isNotEmpty(o)) {
                                //List<EntityMap> detailList = hyRemoteOrderService.purchasePaymentDetailList(busCwErp.getCompanyErpInstance(), mxNo, busErpOrderDetails.getProductCode(), busErpOrderDetails.getProductBatch());
                                Map<String, List<EntityMap>> detailList = entityMaps.stream().filter(b -> ObjectUtil.isNotNull(b.get("mxNo"))).collect(Collectors.groupingBy(b -> b.get("mxNo").toString() + "#" + b.get("productCode").toString() + "#" + b.get("productBatch").toString()));
                                if (CollUtil.isNotEmpty(detailList)) {
                                    for (String s : detailList.keySet()) {
                                        List<EntityMap> entityMaps1 = detailList.get(s);
                                        for (EntityMap entityMap : entityMaps1) {
                                            //BigDecimal productPrice = entityMap.get("productPrice");
                                            //int saleNum = entityMap.get("saleNum");
                                            //BigDecimal saleAmount = entityMap.get("saleAmount");
                                            //String productCode = entityMap.get("productCode");
                                            //String productBatch = entityMap.get("productBatch");

                                            //if (busErpOrderDetails.getProductCode().equals(productCode) && busErpOrderDetails.getProductBatch().equals(productBatch)) {
                                            //    busErpOrderDetails.setProductPrice(productPrice);

                                            if (busErpOrderDetails.getProductCode().equals(entityMap.get("productCode")) && busErpOrderDetails.getProductBatch().equals(entityMap.get("productBatch"))) {

                                                BigDecimal saleAmount = entityMap.get("receiptAmount");
                                                BigDecimal divide = saleAmount.divide(busErpOrderDetails.getProductPrice(), 2, BigDecimal.ROUND_HALF_UP);

                                                busErpOrderService.update(new UpdateWrapper<BusErpOrder>().lambda().set(BusErpOrder::getUpdateTime, DateUtil.date()).set(BusErpOrder::getReceiptAmount, saleAmount).eq(BusErpOrder::getOrderType, VoucherTypeEnum.Fk.getCode()).eq(BusErpOrder::getOrderNo, entityMap.get("orderNo")));
                                                busErpOrderDetails.setProductNum(divide.intValue());
                                                busErpOrderDetails.setProductSaleAmount(saleAmount);
                                                busErpOrderDetails.setUpdateTime(entityMap.get("receiptDate"));
                                                break;
                                            }
                                            //}
                                        }
                                    }

                                }
                                busErpOrderDetails.setCreateTime(DateUtil.date());
                                busErpOrderDetails.setOrderType(VoucherTypeEnum.Fk.getCode());
                                busErpOrderDetails.setErpDbName(busCwErp.getCompanyErpInstance());
                                busErpOrderDetails.setHyDwCode(busCwErp.getCompanyCode());
                                busErpOrderDetailsList.add(busErpOrderDetails);
                            }
                        });
                    }


                    busErpOrderDetailsService.saveBatch(busErpOrderDetailsList);

                }
            }
        }
    }


    // 收款凭证 查询入库订单
    @Scheduled(cron = "0 0/2 8-22 * * ?")
    public void payableOrderTasks() {
        // 1 查询当天ERP销售订单
        // 2 订单详情记录到本地
        // 3 根据订单信息找到单位 、商品信息
        // 4 查询单位对应的凭证编号
        // 5 生成凭证
        String currentDay = getCurrentDay();
        List<SysCompany> cwErpList = getSysCompanies();
        Map<String, Long> erpMap = cwErpList.stream().collect(Collectors.toMap(c -> c.getCompanyErpInstance(), c -> c.getCompanyId()));

        for (SysCompany busCwErp : cwErpList) {
            QueryWrapper<BusErpOrder> qw = new QueryWrapper<>();
            qw.eq("date_format(createTime,'%Y-%m-%d')", DatePattern.NORM_DATE_FORMAT.format(DateUtil.date())).lambda()
                .eq(BusErpOrder::getHyDwCode, busCwErp.getCompanyCode())
                .eq(BusErpOrder::getOrderType, VoucherTypeEnum.Sk.getCode());
            List<BusErpOrder> currentErpOrderList = busErpOrderService.list(qw);
            List<String> orderNos = currentErpOrderList.stream().map(BusErpOrder::getOrderNo).collect(Collectors.toList());
            List<EntityMap> entityMaps = hyRemoteOrderService.receiptPaymentOrderList("1", busCwErp.getCompanyErpInstance(), currentDay, CollUtil.isEmpty(orderNos) ? null : orderNos);


            Map<String, String> mxCollect = entityMaps.stream().filter(b -> ObjectUtil.isNotNull(b.get("mxNo"))).collect(Collectors.toMap(b -> b.get("orderNo").toString(), b -> b.get("mxNo").toString(), (v1, v2) -> v1));

            if (CollUtil.isEmpty(entityMaps)) {
                continue;
            }
            orderNos = entityMaps.stream().map(e -> e.get("orderNo").toString()).distinct().collect(Collectors.toList());
            if (CollUtil.isEmpty(orderNos)) {
                return;
            }
            //按单据勾对
            List<String> orderNos1 = entityMaps.stream().filter(b -> ObjectUtil.isNull(b.get("mxNo"))).map(b -> b.get("orderNo").toString()).collect(Collectors.toList());
            //明细勾对
            List<String> orderNos2 = entityMaps.stream().filter(b -> ObjectUtil.isNotNull(b.get("mxNo"))).map(b -> b.get("orderNo").toString()).collect(Collectors.toList());
            //while (iterator.hasNext()) {
            for (int w = 0; w < orderNos.size(); w++) {
                String orderNo11 = orderNos.get(w);
                //String orderNo = iterator.next();
                List<EntityMap> list = hyRemoteOrderService.purchasePayableOrderList(busCwErp.getCompanyErpInstance(), null, Arrays.asList(orderNo11));
                if (CollUtil.isEmpty(list)) {
                    return;
                }
                List<BusErpOrder> busErpOrderList = new ArrayList<>();
                list.forEach(item -> {
                    BusErpOrder busErpOrder = BeanUtil.fillBeanWithMap(item, new BusErpOrder(), false);
                    BusErpOrder check = busErpOrderService.findByOrderNoAndType(busErpOrder.getOrderNo(), VoucherTypeEnum.Sk.getCode());
                    if (FlymeUtils.isNotEmpty(check)) {
                        busErpOrder.setOrderId(check.getOrderId());
                    }
                    busErpOrder.setOrderType(VoucherTypeEnum.Sk.getCode());
                    busErpOrder.setErpDbName(busCwErp.getCompanyErpInstance());
                    busErpOrder.setHyDwCode(busCwErp.getCompanyCode());
                    busErpOrder.setCreateTime(DateUtil.date());
                    busErpOrder.setCompanyId(erpMap.get(busCwErp.getCompanyErpInstance()));
                    busErpOrderList.add(busErpOrder);
                });
                busErpOrderService.saveOrUpdateBatch(busErpOrderList);
                List<BusErpOrderDetails> busErpOrderDetailsList = new ArrayList<>();

                if (orderNos1.contains(orderNo11)) {
                    Map<String, List<EntityMap>> detailList = entityMaps.stream().filter(b -> ObjectUtil.isNull(b.get("mxNo"))).collect(Collectors.groupingBy(b -> b.get("orderNo").toString()));

                    List<EntityMap> orderDetailList = hyRemoteOrderService.purchasePayableOrderDetailList(busCwErp.getCompanyErpInstance(), null, Arrays.asList(orderNo11));
                    orderDetailList.forEach(item -> {
                        BusErpOrderDetails busErpOrderDetails = BeanUtil.fillBeanWithMap(item, new BusErpOrderDetails(), false);
                        busErpOrderDetails.setOrderType(VoucherTypeEnum.Sk.getCode());
                        busErpOrderDetails.setErpDbName(busCwErp.getCompanyErpInstance());
                        busErpOrderDetails.setHyDwCode(busCwErp.getCompanyCode());
                        busErpOrderDetails.setCreateTime(DateUtil.date());
                        if (CollUtil.isNotEmpty(detailList)) {
                            for (String s : detailList.keySet()) {
                                List<EntityMap> entityMaps1 = detailList.get(s);
                                for (EntityMap entityMap : entityMaps1) {
                                    if (busErpOrderDetails.getOrderNo().equals(entityMap.get("orderNo"))) {
                                        busErpOrderDetails.setUpdateTime(entityMap.get("receiptDate"));
                                        break;
                                    }
                                }
                            }
                        }
                        busErpOrderDetailsList.add(busErpOrderDetails);
                    });
                }
                if (orderNos2.contains(orderNo11)) {
                    String mxNo = mxCollect.get(orderNo11);
                    //按明细勾对
                    Map<String, String> proCollect = entityMaps.stream().filter(b -> ObjectUtil.isNotNull(b.get("mxNo"))).collect(Collectors.toMap(b -> b.get("productCode").toString() + "#" + b.get("productBatch").toString(), b -> b.get("productBatch").toString(), (v1, v2) -> v1));
                    List<EntityMap> orderDetailList3 = hyRemoteOrderService.purchasePayableOrderDetailList(busCwErp.getCompanyErpInstance(), null, Arrays.asList(orderNo11));
                    orderDetailList3.forEach(item -> {


                        BusErpOrderDetails busErpOrderDetails = BeanUtil.fillBeanWithMap(item, new BusErpOrderDetails(), false);
                        String o = proCollect.get(busErpOrderDetails.getProductCode() + "#" + busErpOrderDetails.getProductBatch());
                        if (StrUtil.isNotEmpty(o)) {
                            //List<EntityMap> detailList = hyRemoteOrderService.purchasePaymentDetailList(busCwErp.getCompanyErpInstance(), mxNo, busErpOrderDetails.getProductCode(), busErpOrderDetails.getProductBatch());
                            Map<String, List<EntityMap>> detailList = entityMaps.stream().filter(b -> ObjectUtil.isNotNull(b.get("mxNo"))).collect(Collectors.groupingBy(b -> b.get("mxNo").toString() + "#" + b.get("productCode").toString() + "#" + b.get("productBatch").toString()));
                            if (CollUtil.isNotEmpty(detailList)) {
                                for (String s : detailList.keySet()) {
                                    List<EntityMap> entityMaps1 = detailList.get(s);
                                    for (EntityMap entityMap : entityMaps1) {
                                        //BigDecimal productPrice = entityMap.get("productPrice");
                                        //int saleNum = entityMap.get("saleNum");
                                        //BigDecimal saleAmount = entityMap.get("saleAmount");
                                        //String productCode = entityMap.get("productCode");
                                        //String productBatch = entityMap.get("productBatch");

                                        //if (busErpOrderDetails.getProductCode().equals(productCode) && busErpOrderDetails.getProductBatch().equals(productBatch)) {
                                        //    busErpOrderDetails.setProductPrice(productPrice);

                                        if (busErpOrderDetails.getProductCode().equals(entityMap.get("productCode")) && busErpOrderDetails.getProductBatch().equals(entityMap.get("productBatch"))) {

                                            BigDecimal saleAmount = entityMap.get("receiptAmount");
                                            BigDecimal divide = saleAmount.divide(busErpOrderDetails.getProductPrice(), 2, BigDecimal.ROUND_HALF_UP);

                                            busErpOrderService.update(new UpdateWrapper<BusErpOrder>().lambda().set(BusErpOrder::getReceiptAmount, saleAmount).eq(BusErpOrder::getOrderType, VoucherTypeEnum.Sk.getCode()).eq(BusErpOrder::getOrderNo, entityMap.get("orderNo")));
                                            busErpOrderDetails.setProductNum(divide.intValue());
                                            busErpOrderDetails.setProductSaleAmount(saleAmount);
                                            busErpOrderDetails.setUpdateTime(entityMap.get("receiptDate"));

                                            break;
                                        }
                                        //}
                                    }
                                }

                            }
                            busErpOrderDetails.setCreateTime(DateUtil.date());
                            busErpOrderDetails.setOrderType(VoucherTypeEnum.Sk.getCode());
                            busErpOrderDetails.setErpDbName(busCwErp.getCompanyErpInstance());
                            busErpOrderDetails.setHyDwCode(busCwErp.getCompanyCode());
                            busErpOrderDetailsList.add(busErpOrderDetails);
                        }
                    });
                }


                busErpOrderDetailsService.saveBatch(busErpOrderDetailsList);


            }

        }

    }


    public static void main(String[] args) {
        String PZBHStr = String.format("%05d", 21);
        System.out.println(PZBHStr);
        System.out.println("Z111".indexOf("Z"));
        System.out.println(DatePattern.NORM_DATE_FORMAT.format(DateUtil.date()));
        System.out.println("Y1A京A001".charAt(0));
        System.out.println(Character.isLowerCase("Y1A京A001".toLowerCase().charAt(0)));
        System.out.println((Character.isLowerCase("Y1A京A001".charAt(0)) || Character.isUpperCase("Y1A京A001".charAt(0))));


        BigDecimal JE = new BigDecimal(5.00).multiply(new BigDecimal(10.80)).setScale(2, RoundingMode.HALF_UP);


        System.out.println(JE);
        String month = "2023-04";
        System.out.println(month.substring(0, 4) + "-" + month.substring(5, 7) + "-01");
        System.out.println(DateUtil.parse("20230401"));

        System.out.println(DateUtil.format(DateUtil.offsetMonth(DateUtil.parse("2023-04-01".replace("-", "")), -1), DatePattern.NORM_DATETIME_PATTERN).substring(0, 7));

    }

    @Scheduled(cron = "0 */2 09-22 * * ?")
    public void updateOrderSendState() {
        System.out.println("##################################同步发货状态########################################");
        orderService.syncSendState();
    }

    @Scheduled(cron = "0 0/1 09-23 * * ?")
    public void syncInsertOrder() {
        System.out.println("##################################同步订单到海鹰系统########################################");
       // orderService.syncInsertOrder();
        //orderService.syncBackOrder();
    }

    @Scheduled(cron = "0 30 12 * * ?")
    //@Scheduled(cron = "0 0 10-19 ? * MON-FRI")
    public void updateHyCustom() {
        System.out.println("##################################同步海鹰客商资料########################################");
        List<SysCompany> cwErpList = getSysCompanies();
        if (FlymeUtils.isNotEmpty(cwErpList)) {
            for (SysCompany company : cwErpList) {
                customService.syncHyCustom(company);
            }
        }
    }
}